package com.opal.utils;

import com.opal.consts.CommonConst;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;

import com.opal.system.entity.table.OpalUser;

public class UserUtils {
	//添加用户处理密码:获取随机盐和处理后的密码密码
		public static OpalUser getNewUser(OpalUser opalUser) {
			// shiro框架的加密算法，用Shiro自带的工具类，做生成盐，两次md5的做法
			String password = opalUser.getUserPassword();
			if(!StringUtils.isBlank(password)) {
				// 两次md5算法 md5(md5(...))
				int times = 2; 
				//随机盐
				String salt= new SecureRandomNumberGenerator().nextBytes().toString(); 
				opalUser.setUserSalt(salt);
				// md5算法
				String algorithmName = "md5"; 
				//使用shiro内部方法获取处理的密码
				String encodedPassword = new SimpleHash(algorithmName, password, salt, times).toString();
				//把生成的密码放入opalUser中
				opalUser.setUserPassword(encodedPassword);
			}
			return opalUser;
		}

	//处理密码获取和数据库一致的密码
	public static String getNewPassword(String password,String salt) {
		if(!StringUtils.isBlank(password)) {
			int times = 2;
			String algorithmName = "md5";
			return new SimpleHash(algorithmName, password, salt, times).toString();
		}
		return null;
	}

		public static OpalUser getSessionUser() {
		      Subject subject = SecurityUtils.getSubject();
		      Object object = subject.getPrincipal();
		      if(object !=null) {
		    	  OpalUser user=(OpalUser)object ;  
		    	  return user;
		      }
		      return null;
		}
		
		public static Long getSessionUserId() {
		      Subject subject = SecurityUtils.getSubject();
		      Long userId = (Long) subject.getSession().getAttribute(CommonConst.USERID);
		      return userId;
		}
}
